package middleware

import (
	"strings"

	"gitee.com/youkelike/ziam/zcode/zcode"
	"gitee.com/youkelike/ziam/zerrors"
	"gitee.com/youkelike/ziam/zutils/response"
	"github.com/gin-gonic/gin"
)

func NewAutoAuth(basic, jwt gin.HandlerFunc) gin.HandlerFunc {
	return func(c *gin.Context) {

		header := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
		if len(header) != 2 {
			response.Write(c, zerrors.WithCode(zcode.ErrSignatureInvalid, "Authorization header format is wrong."), nil)
			c.Abort()
			return
		}

		switch header[0] {
		case "Basic":
			basic(c)
		case "Bearer":
			jwt(c)
		default:
			response.Write(c, zerrors.WithCode(zcode.ErrSignatureInvalid, "unrecognized Authorization header."), nil)
			c.Abort()
			return
		}

		c.Next()
	}
}
